package com.jason.library.scope

/**
 * @description: LetScopeFunctionMain
 *
 * @author ChenBaoyang
 * @date 6/30/21 14:04
 */
object LetScopeFunctionMain {

    @JvmStatic
    fun main(args: Array<String>) {
        characteristic1()
        characteristic2()
        characteristic3()
        characteristic4()
    }

}

/**
 * 特性一：let默认是有返回语句
 */
fun characteristic1() {
    val book = Book().let {
        it.name = "《计算机网络》"
        "This book is ${it.name}" //返回语句
    }
    println(book)

    val book1 = Book().let {
        it.name = "《计算机网络》"
        //上面是赋值语句，所以默认返回：kotlin.Unit
    }
    println(book1)
}

/**
 * 特性二：let可用于空安全检查
 */
var name: String? = null
fun characteristic2() {
    //设置name为一个可空字符串，利用name?.let来进行空判断，只有当name不为空时，逻辑才能走进let函数块中。
    val nameLength = name?.let {
        it.length
    } ?: "name为空时的值"
    println(nameLength)
}

/**
 * 特性三：let可对调用链的结果进行操作
 */
fun characteristic3() {
    //获取数组列表中长度大于3的值,并且将长度打印
    /*val numbers = mutableListOf("One","Two","Three","Four","Five")
    val resultsList = numbers.map { it.length }.filter { it > 3 }
    print(resultsList)*/
    //相比上面，使用let后可以直接对数组列表中长度大于3的值进行打印，去掉了变量赋值这一步
    val numbers = mutableListOf("One","Two","Three","Four","Five")
    numbers.map { it.length }.filter { it > 3 }.let {
        println(it)
    }
}

/**
 * 特性四：let可以将“it”重命名为一个可读的lambda参数
 */
fun characteristic4() {
    //将it重命名为book
    val book = Book().let {book ->
        book.name = "《计算机网络》"
    }
    print(book)
}


class Book() {
    var name = "《数据结构》"
    var price = 60
    fun displayInfo() = println("Book name : $name and price : $price")
}